import { ref , onMounted } from 'vue'

type Params = {
    ms:number,
    immediate?:boolean
}


export const useCount = ({
    ms,
    immediate

}: Params) => {
    const second = ref(ms)
    const count = ref('00:00:00')
    const isFinish = ref(false)
    let timer: number
    const format = () => {
        const h = Math.floor(second.value / 1000 / 60 / 60 )
        const m = Math.floor(second.value / 1000 /60 % 60)
        const s = Math.floor(second.value / 1000 % 60)


        count.value = `${h} : ${m} :${s}`
    }




    const start = () => {
        timer = setInterval(() => {
            if(isFinish.value) return 
            second.value -=1000
            if(second.value <=0) {
                clearInterval(timer)
                isFinish.value = true
            }

            format()
        },1000)
    }

    onMounted(()=>{
        if(immediate) {
            start()
        }

    })



    const stop = () => {
        clearInterval(timer)
    }









    return {
        count,
        start,
        stop,
        isFinish
    }
}